package org.gd.hellojaxb.privat24.cardlist;

import org.gd.hellojaxb.utils.Marshall;
import org.gd.hellojaxb.utils.MarshallProperties;

import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement(name = "doc")
@XmlAccessorType(XmlAccessType.NONE)
public class SCardList {

    private List<SRating> ratings = new ArrayList<SRating>();
    private List<SCardListItem> cardList = new ArrayList<SCardListItem>() {
        @Override
        public boolean add(SCardListItem sCardListItem) {
            ratings.add(new SRating()
                    .setNumber(sCardListItem.getAccount().getCard())
                    .setRate((ratings.size()+1)*2)
                    .setDate(null)
                    .setAmt(sCardListItem.getDynamic()));
            return super.add(sCardListItem);
        }
        @Override
        public SCardListItem remove(int index) {
            ratings.remove(index);
            for(int i=0; i<ratings.size(); i++) {
                ratings.get(i).setRate((i+1)*2);
            }
            return super.remove(index);
        }
    };

    public SCardList() {
        super();
    }

    @XmlElementWrapper(name = "list")
    @XmlElement(name = "row")
    public List<SCardListItem> getCardList() {
        return cardList;
    }

    @XmlElementWrapper(name = "ratings")
    @XmlElement(name = "card")
    @SuppressWarnings("unused")
    public List<SRating> getRatings() {
        return ratings;
    }

    public boolean isEmpty() {
        return cardList.isEmpty();
    }

    public int size() {
        return cardList.size();
    }

    public void add(SCardListItem cardListItem) {
        cardList.add(cardListItem);
    }

    public SCardListItem get(int index) {
        return cardList.get(index);
    }

    public SCardListItem getByCardNumber(String card) {
        for(SCardListItem cardListItem: cardList) {
            if(cardListItem.getAccount().getCard().equals(card)) {
                return cardListItem;
            }
        }
        return null;
    }

    public SCardListItem remove(int index) {
        return cardList.remove(index);
    }

    @SuppressWarnings("unused")
    public SCardListItem removeByCardNumber(String card) {
        for (int i=0; i<size(); i++) {
            if(cardList.get(i).getAccount().getCard().equals(card)) {
                SCardListItem oldValue = cardList.get(i);
                cardList.remove(i);
                return oldValue;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        try {
            return Marshall.getInstance().marshal(this, MarshallProperties.WITHOUT_XML_HEADER);
        } catch (Exception e) {
            return super.toString();
        }
    }
}
